package com.sprint.controller;

import com.sprint.entities.CommonResult;
import com.sprint.entities.Payment;
import com.sprint.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j //打印日志
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;
    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("*********插入结果"+result);
        if(result>0) {
            return new CommonResult(200, "插入数据库成功 端口："+ serverPort, result );
        }
        else
        {
            return new CommonResult(404, "保存失败",null);
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable Long id){
        Payment result = paymentService.getPaymentById(id);
        log.info("*********查询结果"+result);
        if(result != null) {
            return new CommonResult(200, "查询成功 端口："+ serverPort, result );
        }
        else
        {
            return new CommonResult(404, "查询无记录，查询记录："+ id,null);
        }
    }
    @GetMapping("/discovery")
    public  Object discovery(){

        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*****" + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getUri() + "---- ------" +   instance.getServiceId());
        }
        return this.discoveryClient;
    }
    @GetMapping("/lb")
    public  String getLb() {
        return serverPort;
     }


    }
